package com.hlcl.huaji.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import com.elcl.activity.BaseActivity;
import com.elcl.network.AppContext;
import com.elcl.util.DateUtil;
import com.elcl.util.StringUtils;
import com.elcl.util.UriUtils;
import com.elcl.util.viewutils.WindowUtils;
import com.elcl.widget.comp.toast.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.hlcl.huaji.R;
import com.hlcl.huaji.ctrl.DialogUtils;
import com.hlcl.huaji.ctrl.adapter.PicShowAdapter;
import com.hlcl.huaji.ctrl.comp.MyGridView;
import com.hlcl.huaji.ctrl.toast.SuccessToastUtils;
import com.hlcl.huaji.model.Order;
import com.hlcl.huaji.model.OrderDetail;
import com.hlcl.huaji.server.NetCode;
import com.hlcl.huaji.server.OrderServer;
import com.hlcl.huaji.utils.HideUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lichunlin on 2018/5/21.
 * 订单详情
 */

public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private String orderId = "";//订单的id
    private OrderDetail orderDetail;
    private int orderType = 0;//订单的类型
    private Order order;
    private OrderServer orderServer = new OrderServer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_order_detail);

        orderId = getIntent().getStringExtra("orderId");
        initScrollView();
        getOrderServer();
        WindowUtils windowUtils = new WindowUtils();
        windowUtils.fullScreen(OrderDetailActivity.this);
    }

    private void initScrollView() {
        final ScrollView scrollView = findViewById(R.id.scrollView);
        netHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, 0);
            }
        },300);
    }

    private void getOrderServer() {
        if (StringUtils.isNotBlank(orderId)) {
            OrderServer.getInstance().getOrderDetailServer(netHandler, orderId);
        } else {
            ToastUtils.showToast("获取订单号失败");
            finish();
        }
    }

    @Override
    protected void praseJson(int reqId, String json) {
        if (reqId == NetCode.ID_ORDER_DETAIL) {//订单详情
            orderDetail = gson.fromJson(json, new TypeToken<OrderDetail>() {
            }.getType());
            if (null != orderDetail) {
                initOrderDetailView(orderDetail);
            }
        } else if (reqId == NetCode.ID_ORDER_MODIFY_STATE) {//修改订单状态
            if (clickState == 3) {//点击接单
                SuccessToastUtils.showToast("恭喜您接单成功");
                refreshOrderList();
                finish();
            } else if (clickState == 4) {//点击开始维修
                getOrderServer();
                refreshOrderList2();
                ToastUtils.showToast("开始维修");
            } else if (clickState == 7) {//点击取消订单
                ToastUtils.showToast("取消订单成功");
                refreshOrderList3();
                finish();
            }
        }
    }

    private void refreshOrderList() {
        OrderFragment orderFragment1 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(0);
        orderFragment1.isNeedRefresh = true;

        OrderFragment orderFragment2 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(1);
        orderFragment2.isNeedRefresh = true;

        OrderFragment orderFragment3 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(2);
        orderFragment3.isNeedRefresh = true;
    }

    private void refreshOrderList2() {
        OrderFragment orderFragment2 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(1);
        orderFragment2.isNeedRefresh = true;

        OrderFragment orderFragment3 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(2);
        orderFragment3.isNeedRefresh = true;

        OrderFragment orderFragment4 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(3);
        orderFragment4.isNeedRefresh = true;
    }

    private void refreshOrderList3() {
        OrderFragment orderFragment2 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(1);
        orderFragment2.isNeedRefresh = true;

        OrderFragment orderFragment3 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(2);
        orderFragment3.isNeedRefresh = true;
    }


    private void initOrderDetailView(OrderDetail orderDetail) {
        if (null != orderDetail) {
            order = orderDetail.getjData();
            if (null != order) {
                orderType = order.getState();
                initBaseView();
            }
        }
    }

    private TextView tv_order_corprotion;

    private void initBaseView() {
        tv_order_corprotion = findViewById(R.id.tv_order_corprotion);
        initBtnView();
        initTopOrderInfoView();
        initUserInfoView();
        initContactView();
        initRepairView();
        initPicView();
    }

    private TextView tv_left, tv_right;

    //初始化底部的button
    private void initBtnView() {
        tv_left = findViewById(R.id.tv_left);
        tv_left.setOnClickListener(this);
        tv_right = findViewById(R.id.tv_right);
        tv_right.setOnClickListener(this);
        if (orderType == 1 || orderType == 2) {//如果是未抢单
            tv_left.setText("抢单");
            tv_right.setVisibility(View.GONE);
        } else if (orderType == 3) {//如果是已接单，处理中

        } else {
            tv_left.setVisibility(View.GONE);
            tv_right.setVisibility(View.GONE);
            setVisibility(R.id.ll_bottom,View.GONE);
        }
    }

    //    1、未抢单(快速抢修)   2、未抢单(预约维修)        3、已抢单（待处理）4、（处理中）5、待评价   6、已完成（维修成功）  7、已取消 8、已完成(维修失败)
    //初始化顶部的个人信息接口
    private void initTopOrderInfoView() {
        if (orderType == 1) {//如果还未抢单，不显示
            setVisibility(R.id.view_order_detail_getuserinfo, View.GONE);
        } else {//否则的话，判断当前接单者身份是否为自己，是的话，继续，否则的话，button显示已抢单
            if (order.getOrder_get_user_id() == AppContext.getUid()) {
                if (orderType == 3) {//待处理
                    setText(R.id.tv_order_state, "抢单成功，等待维修");
                } else if (orderType == 4) {//处理中
                    setText(R.id.tv_order_state, "正在维修");
                } else if (orderType == 12) {//已完成
                    if (order.getIs_comment_jishi() == 0) {//已完成
                        if (order.getRepairResult() == 1) {//成功
                            setText(R.id.tv_order_state, "维修成功，待评价");
                        } else if (order.getRepairResult() == 2) {//失败
                            setText(R.id.tv_order_state, "维修失败，待评价");
                        }
                        tv_order_corprotion.setVisibility(View.VISIBLE);
                        tv_order_corprotion.setText("待评价");
                    } else if (order.getIs_comment_jishi() == 1) {//已评价
                        if (order.getRepairResult() == 1) {//成功
                            setText(R.id.tv_order_state, "维修成功，已评价");
                        } else if (order.getRepairResult() == 2) {//失败
                            setText(R.id.tv_order_state, "维修失败，已评价");
                        }
                        tv_order_corprotion.setVisibility(View.VISIBLE);
                        tv_order_corprotion.setText("查看评价");
                    }
                    tv_order_corprotion.setOnClickListener(this);
                } else if (orderType == 7) {//已取消
                    setText(R.id.tv_order_state, "订单已取消");
                }

                String orderGetDate = order.getOrder_get_date();
                long long_orderGetDate = 0;
                if (StringUtils.isNotBlank(orderGetDate)) {
                    long_orderGetDate = Long.parseLong(orderGetDate);
                    orderGetDate = DateUtil.getDateFormat(long_orderGetDate, DateUtil.YYYY_MM_DD_HH_MM);
                } else {
                    orderGetDate = order.getOrderGetDate();
                }

                setText(R.id.tv_order_get_date, "抢单时间:" + orderGetDate);
                setText(R.id.tv_order_number, "订单编号:" + order.getOrderid());
            } else {
                setVisibility(R.id.view_order_detail_getuserinfo, View.GONE);
                tv_left.setVisibility(View.GONE);
                tv_right.setText("已被抢单");
                tv_right.setClickable(false);
            }
        }
    }

    //初始化中间的view
    private void initUserInfoView() {
        setText(R.id.tv_order_name, order.getCreaterName());
        if (order.getType().equals("0")) {//快速维修
            setText(R.id.tv_order_date, "下单时间:" + DateUtil.getDateFormat(order.getOrderTime(), DateUtil.YYYY_MM_DD_HH_MM));
        } else if (order.getType().equals("1")) {//预约维修
            setText(R.id.tv_order_date, "预约时间:" + DateUtil.getDateFormat(order.getReserveTime(), DateUtil.YYYY_MM_DD_HH_MM));
        }
        setText(R.id.tv_order_type, order.getRepairContent());
        long priceAll = (long) (order.getPrice() + order.getAdditionalPrice());
        setText(R.id.tv_order_price, "￥" + priceAll);
        String orderType = order.getType();
        String orderFixType = "";
        if (orderType.equals("0")) {
            orderFixType = "快速维修";
        } else if (orderType.equals("1")) {
            orderFixType = "预约维修";
        }
        setText(R.id.tv_order_state_get, orderFixType);
    }

    //初始化联系方式的view
    private void initContactView() {
        String phone = order.getCreaterPhone();
        String companyName = order.getCreaterCompany();
        String repairAdress = order.getRepairAddress();
        boolean isClickPhone = true;//是否可以拨打电话
        if (orderType == 1 || orderType == 2) {//当未接单的时候，不显示具体的orderPhone
            phone = HideUtils.getHideContent(phone);
            companyName = HideUtils.getHideContent(companyName);
            repairAdress = HideUtils.getHideContent(repairAdress);
            isClickPhone = false;
        } else {
            if (order.getOrder_get_user_id() != AppContext.getUid()) {//如果是当前是自己的单子
                phone = HideUtils.getHideContent(phone);
                companyName = HideUtils.getHideContent(companyName);
                repairAdress = HideUtils.getHideContent(repairAdress);
                isClickPhone = false;
            }
        }
        setText(R.id.tv_phone, phone);
        setText(R.id.tv_company_name, companyName);
        setText(R.id.tv_repair_address, repairAdress);
        if (isClickPhone) {//如果可以点击的话，拨打电话
            setListener(R.id.tv_phone, this);
        }
    }


    //初始化维修信息的view
    private void initRepairView() {
        setText(R.id.tv_brand, order.getRepairBrands());//品牌
        setText(R.id.tv_repair_origin, order.getRepairOrigin());//产地
        setText(R.id.tv_repair_number, order.getRepairNumber());//型号
        setText(R.id.tv_repair_system, order.getRepairSystem());//系统
        setText(R.id.tv_break_description, order.getBreakDescription());//故障描述
    }

    //图片和备注信息
    private void initPicView() {
        String picShows = order.getPicShow();
        List<String> list_pic_show = getPicListByString(picShows);
        initGvView(list_pic_show);

        setText(R.id.tv_orde_pic_number, "(" + list_pic_show.size() + ")");
        setText(R.id.tv_remark, order.getRemark());
    }

    //初始化图片的view
    private void initGvView(List<String> list_pic_show) {
        MyGridView gv_pic = findViewById(R.id.gv_pic);
        PicShowAdapter picShowAdapter = new PicShowAdapter(list_pic_show, R.layout.adapter_pic);
        gv_pic.setAdapter(picShowAdapter);
    }

    //将返回的图片的string转换为list<String>
    private List<String> getPicListByString(String picShow) {
        List<String> list_pic = new ArrayList<>();
        if (StringUtils.isNotBlank(picShow)) {
            String[] picShows = picShow.split(",");
            if (null != picShows) {
                for (int i = 0; i < picShows.length; i++) {
                    list_pic.add(picShows[i]);
                }
            } else {
                list_pic.add(picShow);
            }
        }
        return list_pic;
    }


    private int clickState = 0;
    private String[] dialogCancleContent = new String[]{"提示", "如果取消订单，将不再能抢该订单 \n且会自动得到差评，是否确定取消?", "否", "是"};

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left://左边的button
                String content = tv_left.getText().toString();
                if (content.equals("抢单")) {//开始抢单
                    clickState = 3;
                    orderServer.modifyOrderServer(netHandler, orderId, 3);
                } else if (content.equals("开始维修")) {//开始维修
                    clickState = 4;
                    orderServer.modifyOrderServer(netHandler, orderId, 4);
                }
                break;
            case R.id.tv_right://右边边的button
                String contentRight = tv_right.getText().toString();
                if (contentRight.equals("取消订单")) {//取消的订单
                    clickState = 7;
                    DialogUtils.showChooseDialog(this, dialogCancleContent, new DialogUtils.ClickRight() {
                        @Override
                        public void clickSure() {//取消订单
                            orderServer.modifyOrderServer(netHandler, orderId, 7);
                        }

                        @Override
                        public void clickCancle() {

                        }
                    });
                }
                break;
            case R.id.tv_phone://拨打电话
                if (null != order) {
                    if (order.getState() == 1 || order.getState() == 2) {
                        ToastUtils.showToast("未抢单，不能拨打电话");
                    } else {
                        UriUtils.dialPhone(order.getCreaterPhone());
                    }
                }
                break;
            case R.id.tv_order_corprotion://点击评论给的界面
                Intent intent = new Intent(this,CommentActivity.class);
                intent.putExtra("order",order);
                startActivityForResult(intent, 0x111);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x111 && resultCode == RESULT_OK) {
            getOrderServer();
        }
    }
}
